package controller

import (
	"database/sql"
	//"encoding/json"
	"fmt"
	"mbti/model"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

type Answer struct {
	Id         string `json:"id,omitempty"`
	Student_id string `json:"student_id,omitempty"`
	//Student_answer string `json:"student_answer,omitempty"`
	Answer         string            `json:"answer,omitempty"`
	Create_time    string            `json:"create_time,omitempty"`
	Student_answer map[string]string `json:"student_answer,omitempty"`
	//Student_name   string `json:"student_name,omitempty"`
	//College        string `json:"college,omitempty"`
	//Specialize     string `json:"specialize,omitempty"`
	//Student_class  string `json:"student_class,omitempty"`
}

//获取所有测试结果
func GetMBTI(ctx *gin.Context) {
	//offset := ctx.PostForm("offset")
	offset := ctx.Query("offset")
	student_id := ctx.Query("student_id")
	fmt.Println(1, student_id)
	//result, err := model.DB.Query(fmt.Sprintf("select answer.id,student.student_name,student.college,student.specialize,student.student_class,"+
	//	"answer.student_id,answer.student_answer,answer.result,answer.create_time "+
	//	"from answer join student on answer.student_id = student.student_id limit 10 offset %s", offset))
	var result *sql.Rows
	var err error
	if len(student_id) > 0 {

		result, err = model.DB.Query(fmt.Sprintf("select * from answer where student_id =  %s", student_id))
	} else {
		result, err = model.DB.Query(fmt.Sprintf("select * from answer limit 10 offset %s", offset))
	}

	if err != nil {
		fmt.Println("GetExistUser err:", err)
	}

	var ans Answer
	var allAns []Answer
	var moment string
	for result.Next() {

		err = result.Scan(&ans.Id, &ans.Student_id, &moment, &ans.Answer, &ans.Create_time)
		//err = result.Scan(&ans.Id, &ans.Student_id, &ans.Student_name, &ans.College, &ans.Specialize, &ans.Student_class, &ans.Student_answer, &ans.Create_time, &ans.Result)

		moment = strings.Trim(moment, `{`)
		moment = strings.Trim(moment, `}`)
		momentList := strings.Split(moment, ",")
		momentMap := make(map[string]string)
		for i := 0; i < len(momentList); i++ {
			str := momentList[i]
			str = strings.Trim(str, "\"")
			s := strings.Split(str, `":"`)
			momentMap[s[0]] = s[1]
		}
		ans.Student_answer = momentMap
		allAns = append(allAns, ans)
	}

	ctx.JSON(200, gin.H{
		"code": 200,
		"msg":  allAns,
	})

}

//删除测试结果
func DeleteMBTI(ctx *gin.Context) {
	id := ctx.Query("id")

	stmt, err := model.DB.Prepare("delete from answer where id=$1")
	if err != nil {
		fmt.Println("Some amazing wrong happens in preparation for the insert.")
		ctx.JSON(422, gin.H{
			"code": 422,
			"msg":  "删除失败",
		})
		return
	}
	defer stmt.Close()
	res, err := stmt.Exec(id)
	if err != nil {
		fmt.Println("Some amazing wrong happens in the process of doInsertOne.")
		ctx.JSON(422, gin.H{
			"code": 422,
			"msg":  "删除失败",
		})
		return
	}
	num, err := res.RowsAffected()
	if err != nil {
		fmt.Println("Some amazing wrong happens in the affected fo deletion.")
		ctx.JSON(422, gin.H{
			"code": 422,
			"msg":  "删除失败",
		})
		return
	}
	fmt.Println("Successfully add ", num)
	ctx.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

//更新测试结果
func UpdateMBTI(ctx *gin.Context) {
	id := ctx.PostForm("id")
	studentID := ctx.PostForm("studentID")
	result := ctx.PostForm("result")
	timeNow := time.Now().Unix()

	stmt, err := model.DB.Prepare("update answer set student_id= $1,result=$2,create_time=$3 where id=$4")
	if err != nil {
		fmt.Println("Some amazing wrong happens in preparation for the insert.", err)
		ctx.JSON(422, gin.H{
			"code": 422,
			"msg":  "更新失败,该student_id已存在",
		})
		return
	}
	defer stmt.Close()
	res, err := stmt.Exec(studentID, result, timeNow, id)
	if err != nil {
		fmt.Println("Some amazing wrong happens in the process of doInsertOne.", err)
		ctx.JSON(422, gin.H{
			"code": 422,
			"msg":  "更新失败,该student_id已存在或数据有误",
		})
		return
	}
	num, err := res.RowsAffected()
	if err != nil {
		fmt.Println("Some amazing wrong happens in the affected fo deletion.")
		ctx.JSON(422, gin.H{
			"code": 422,
			"msg":  "更新失败",
		})
		return
	}
	fmt.Println("Successfully add ", num)
	ctx.JSON(200, gin.H{
		"code": 200,
		"msg":  "更新成功",
	})
	return
}
